import { useLocation } from 'react-router-dom';
import { routeList } from '@/router/index.jsx';
import StringUtil from '@/utils/string.js';
import { useEffect, useState } from 'react';

function useMatchRouteRule() {
  // 获取当前url
  const { pathname } = useLocation();
  // 路由规则
  const [routeRule, setRouteRule] = useState(null);

  useEffect(() => {
    const rule = findRouteRule(pathname, routeList);
    if (rule) {
      // 如果匹配到了路由规则，则直接返回
      setRouteRule(rule);
    }
  }, [pathname]);

  // 查询路由规则
  function findRouteRule(find, list, parentPath = '') {
    if (!Array.isArray(list)) {
      return find;
    }
    for (const route of list) {
      const rule = (StringUtil.isNotEmpty(parentPath) ? parentPath + '/' : '') + route?.path;
      // 匹配路由规则
      const result = matchRoute(rule, find);
      // 当前地址匹配到路由规则
      if (result) {
        return rule;
      }
      // 未匹配，继续查询子路由
      const children = route?.children;
      if (Array.isArray(children)) {
        return findRouteRule(find, children, rule);
      }
    }
  }

  // 匹配路由规则的函数
  function matchRoute(rule, path) {
    const patterns = generateRoutePatterns(rule);
    for (let pattern of patterns) {
      // 如果直接匹配到路由规则，则返回路由规则
      if (pattern === path) {
        return rule;
      } else {
        const regex = new RegExp(
          '^' +
            pattern.replace(/:[a-zA-Z0-9_\u4e00-\u9fa5-]+/g, '([a-zA-Z0-9_\u4e00-\u9fa5-]+)') +
            '(?!/)$'
        );
        const match = path.match(regex);
        if (match) {
          return rule;
        }
      }
    }
    return null;
  }

  // 生成路由规则匹配路径列表
  function generateRoutePatterns(path) {
    const patterns = [];
    const segments = path.split('?');
    let start = '';
    for (const segment of segments) {
      patterns.push(start + segment);
      start = segment;
    }
    return patterns;
  }

  return routeRule;
}

export default useMatchRouteRule;
